package com.cqz.action;

import com.cqz.dao.BookInfo;
import com.cqz.dao.OrderInfo;
import com.cqz.dao.UserInfo;
import com.cqz.services.BookService;
import com.cqz.services.OrderService;
import com.cqz.services.TagService;
import com.cqz.services.UserService;
import com.cqz.tools.MyJsonConfig;
import com.cqz.tools.Tools;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
public class UpdateAction {

    @Autowired
    private UserService userService;
    @Autowired
    private TagService tagService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private BookService bookService;
    private String whichPanel = "1";

    private static int initLimit = 4;

    /**
     * 更新密码
     * @param httpSession
     * @param user_password
     * @param surePassword
     * @return
     */
    @RequestMapping("updatePasswordAction")
    public String updatePasswordAction(HttpSession httpSession,String user_password,String surePassword){
        int uid=(Integer) httpSession.getAttribute("uid");
        if(Tools.isNull(user_password)||Tools.isNull(surePassword)){
            httpSession.setAttribute("userNameOrPassword","不能提交空密码");
            return "redirect:homeAction?whichPanel="+3;
        }
        if(!user_password.equals(surePassword)){
            httpSession.setAttribute("userNameOrPassword","两次输入的密码不一致");
            return "redirect:homeAction?whichPanel="+3;
        }
        boolean flag=userService.updatePassword(uid,user_password);
        if(flag==false){
            httpSession.setAttribute("userNameOrPassword","重置密码失败");
            return "redirect:homeAction?whichPanel="+3;
        }else return "redirect:homeAction?whichPanel="+3;
    }

    @RequestMapping("updateAddressAction")
    public String updateAddressAction(HttpSession httpSession,String unewaddress){
        int uid=(Integer) httpSession.getAttribute("uid");
        if(Tools.isNull(unewaddress)){
            httpSession.setAttribute("userAddress","不能提交空地址");
            return "redirect:homeAction?whichPanel="+3;
        }
        boolean flag=userService.updateAddress(uid,unewaddress);
        if(flag==false){
            httpSession.setAttribute("userAddress","更新地址失败");
            return "redirect:homeAction?whichPanel="+3;
        }else {
            httpSession.setAttribute("address",unewaddress);
            return "redirect:homeAction?whichPanel="+3;
        }
    }

    /**
     * 更新书籍信息
     * @param httpSession
     * @param bookInfo
     * @param bprice
     * @return
     */
    @RequestMapping("updateBookInfoAction")
    public String updateBookInfoAction(HttpSession httpSession, BookInfo bookInfo,String bprice){
        httpSession.removeAttribute("berror");
        String searchContent=(String)httpSession.getAttribute("searchContent");
        if(Tools.isNull(bookInfo.getBname())){
            httpSession.setAttribute("berror","书名不能为空");
            return "redirect:searchBookeditAction";
        }
        if(Tools.isNull(bookInfo.getBauthor())){
            httpSession.setAttribute("berror","作者名不能为空");
            return "redirect:searchBookeditAction";
        }
        if(Tools.isNull(bookInfo.getBscore())){
            httpSession.setAttribute("berror","评分不能为空或小于0");
            return "redirect:searchBookeditAction";
        }
        if(Tools.isNull(bprice)){
            httpSession.setAttribute("berror","价格不能为空或小于0");
            return "redirect:searchBookeditAction";
        }else {
            bookInfo.setBprice(new BigDecimal(bprice));
        }
        if(bookInfo.getBnum()<0){
            httpSession.setAttribute("berror","库存不能为负");
            return "redirect:searchBookeditAction";
        }
        if(Tools.isNull(bookInfo.getBurl())){
            httpSession.setAttribute("berror","图片路径不能为空");
            return "redirect:searchBookeditAction";
        }
        boolean flag=bookService.updateBookInfo(bookInfo);
        if(flag==false){
            httpSession.setAttribute("berror","修改失败");
        }else {
            httpSession.setAttribute("berror","修改成功");
        }
        return "redirect:searchBookeditAction";
    }

    /**
     * 修改用户标签
     * @param httpSession
     * @param selectCount
     * @param tag_register
     * @param user_tag1
     * @param user_tag2
     * @param user_tag3
     * @param user_tag4
     * @param user_tag5
     * @param user_tag6
     * @return
     */
    @RequestMapping("updateTagAction")
    public String updateTagAction(HttpSession httpSession,String selectCount,
                                  @RequestParam(value = "tag_register",defaultValue = "0") String tag_register,
                                  String user_tag1,String user_tag2,String user_tag3,String user_tag4,String user_tag5,String user_tag6){
        int uid=(Integer) httpSession.getAttribute("uid");
        UserInfo ue=new UserInfo();
        ue.setUid(uid);
        ue.setUtag1(Integer.parseInt(selectCount) >= 1?user_tag1:null);
        ue.setUtag2(Integer.parseInt(selectCount) >= 2?user_tag2:null);
        ue.setUtag3(Integer.parseInt(selectCount) >= 3?user_tag3:null);
        ue.setUtag4(Integer.parseInt(selectCount) >= 4?user_tag4:null);
        ue.setUtag5(Integer.parseInt(selectCount) >= 5?user_tag5:null);
        ue.setUtag6(Integer.parseInt(selectCount) >= 6?user_tag6:null);
        boolean flag=userService.updateByUid(ue);
        if(flag){
            String[] tagList = new String[6];
            tagList[0] = ue.getUtag1()==null?ue.getUtag1():"null";
            tagList[1] = ue.getUtag2()==null?ue.getUtag2():"null";
            tagList[2] = ue.getUtag3()==null?ue.getUtag3():"null";
            tagList[3] = ue.getUtag4()==null?ue.getUtag4():"null";
            tagList[4] = ue.getUtag5()==null?ue.getUtag5():"null";
            tagList[5] = ue.getUtag6()==null?ue.getUtag6():"null";
            httpSession.setAttribute("tagList",tagList);
            httpSession.setAttribute("tagChange","用户标签修改成功！");

//            if(Integer.parseInt(tag_register) != 1)  //表示用户不是初次选择标签，则直接跳转到homeAction就可以了
//                //若是用户修改标签成功，应先立即更新推荐列表，再返回到main.jsp
//                refreshRecommendList();

            if(Integer.parseInt(tag_register) != 1)
                whichPanel = "3";
            return "redirect:homeAction";

        }else {
            return "fail";
        }
    }

    /**
     * 充值
     * @param httpSession
     * @param uamount
     * @return
     */
    @RequestMapping("updateAmountAction")
    public String updateAmountAction(HttpSession httpSession,String uamount){
        httpSession.removeAttribute("mounterror");
        int uid=(Integer) httpSession.getAttribute("uid");
        UserInfo userInfo=userService.findUser(uid);
        if(Tools.isNull(uamount)){
            httpSession.setAttribute("mounterror","充值金额不能为空");
            return "redirect:homeAction?whichPanel="+3;
        }
        BigDecimal amount=userInfo.getUamount();
        BigDecimal add=new BigDecimal(uamount);
        userInfo.setUamount(amount.add(add));

        boolean flag=userService.updateByUid(userInfo);
        if(flag==false){
            httpSession.setAttribute("mounterror","网络故障");
        }else {
            httpSession.setAttribute("money",userInfo.getUamount());
        }

        return "redirect:homeAction?whichPanel="+3;

    }

    /**
     * 初始化和加载更多推荐内容
     * @param model
     * @param request
     * @param httpSession
     * @param user_name
     * @param after_id
     * @param limit
     * @return
     */
    @RequestMapping("recommendAction")
    public String execute(Model model, HttpServletRequest request, HttpSession httpSession,
                          @SessionAttribute(value = "user_name") String user_name,
                          @RequestParam(value = "after_id",defaultValue = "0") String after_id,
                          @RequestParam(value = "limit",defaultValue = "14") String limit) {
        String session_Id = httpSession.getId();
        int uid=(Integer) httpSession.getAttribute("uid");
        UserInfo userInfo=userService.findUser(uid);
        String[]tagList=new String[6];
        tagList[0]=userInfo.getUtag1();
        tagList[1]=userInfo.getUtag2();
        tagList[2]=userInfo.getUtag3();
        tagList[3]=userInfo.getUtag4();
        tagList[4]=userInfo.getUtag5();
        tagList[5]=userInfo.getUtag6();
        httpSession.setAttribute("tagList",tagList);
        httpSession.setAttribute("money",userInfo.getUamount());
        List<String> tags=new ArrayList<>();
        for(int i=0;i<6;i++){
            if(!Tools.isNull(tagList[i])){
                tags.add(tagList[i]);
            }
        }
        List<BookInfo> recommendList=new ArrayList<>();
        List<Integer> bids=tagService.getRecommendTags(tags);
        Iterator<Integer> iterator=bids.iterator();
        int i=0,j=0;
        int af_id=Integer.parseInt(after_id),lid=Integer.parseInt(limit);
        while (iterator.hasNext()){
            if(i<af_id){
                i++;
                iterator.next();continue;
            }else {
                if(j<lid){
                    BookInfo bookInfo=bookService.getBookById(iterator.next());
                    recommendList.add(bookInfo);
                    j++;
                }else {
                    break;
                }
            }
        }
        if (Integer.parseInt(after_id) >= initLimit) {
            String appendJson = JSONArray.fromObject(recommendList, MyJsonConfig.cfg).toString();
            request.setAttribute("appendJson",appendJson);
            return "forward:recommendAppendAction";
        }
        else {
            model.addAttribute("recommendList",recommendList);
            return "main";
        }
    }

    /**
     * 加载更多推荐内容
     * @param appendJson
     * @return
     */
    @RequestMapping(value = "recommendAppendAction",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String recommendAppendAction(@RequestAttribute("appendJson") String appendJson) {
        return appendJson;
    }

    /**
     * 更新订单信息
     * @param page
     * @param userid
     * @param bid
     * @param ostate
     * @param sdate
     * @param edate
     * @param oid
     * @param ocstate
     * @param model
     * @return
     */
    @RequestMapping("updateOrderAction")
    public String updateOrderAction(String page,String userid,String bid,String ostate,
                                       String sdate,String edate,String oid,String ocstate, Model model){
        model.addAttribute("uid",userid);model.addAttribute("bid",bid);model.addAttribute("ostate",ostate);
        model.addAttribute("sdate",sdate);model.addAttribute("edate",edate);model.addAttribute("page",page);
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setOid(Integer.parseInt(oid));
        orderInfo.setOstate(ocstate);
        boolean flag=orderService.updateOrder(orderInfo);
        if(flag==true){
            return "redirect:searchOrderAction";
        }else {
            model.addAttribute("userid",userid);
            model.addAttribute("oid",oid);
            return "redirect:searchOneOrderAction";
        }
    }

}
